<?php
/*
 *      abtcache.class.php
 *      
 *      Copyright 2009 Alberto Berroteran <ashrey10@yahoo.es>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
/*/




class ABTCache extends ABTemplate{
	public $s_cachedir = '';
	public $b_removews = false;

	function __construct($s_tpl, $s_view, $i_time, $s_dir='', $b_removews=false, $cb_func = null){
		parent::__construct($s_tpl, $s_view, $cb_func);
		$this->i_expire = $i_time;
		$this->s_cachedir =$s_dir;
		$this->b_removews = $b_removews;
		$s_page = sha1($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
		$s_file = $this->s_cachedir.$s_page;
		if(file_exists($s_file)){
			$lasttime= (int)filemtime($s_file);
			if((time() - $lasttime) < $this->i_expire){
				header('X-ABCache: ok');
				readfile($s_file);
				die();
			}
		}		
	}
	
	protected function finish($s_data){
		$s_page = sha1($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
		$s_file = $this->s_cachedir.$s_page;
		$s_data = ($this->b_removews)?preg_replace('/[\t\n]*/', '', $s_data):$s_data;
		if(is_writable($this->s_cachedir)){
			$fp = fopen($s_file, 'w');
			fwrite ($fp, $s_data );
			fclose ($fp);
			clearstatcache();
		}
	
		return parent::finish($s_data);
	}
}
		/*if(!empty($this->filesent)){
			if (file_exists($this->filesent)){
				$etag = sha1(filesize($this->filesent).filemtime($this->filesent));
				header('ETag: '. $etag);
				if($_SERVER['HTTP_IF_NONE_MATCH'] == $etag){
					header('HTTP/1.0 304 Not Modified');
					exit;
				} 
			}
		}*/
?>
